import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getConnection } from 'typeorm';
import { UserEntity } from './user.entity';
import { RoleEntity } from 'src/roles/role.entity';

export interface CommonObjectProps {
  [key: string]: any;
}

@Injectable()
export class UsersService {
  // 向类中注入 userRepository 属性
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) {}

  // 添加
  async createUser(data: CommonObjectProps): Promise<UserEntity> {
    return await this.userRepository.save(data);
  }
  // 列表
  async userList(): Promise<UserEntity[]> {
    return await this.userRepository.find({ relations: ['posts', 'roles'] });
  }

  // 查单个
  async user(id: number): Promise<UserEntity> {
    return await this.userRepository.findOne({ where: { id: id } });
  }

  // 更新
  async update(id: number, user: CommonObjectProps) {
    const result = await getConnection()
      .createQueryBuilder()
      .update(UserEntity)
      .set(user)
      .where('id=:id', { id })
      .execute();
    return result;
  }

  // 删除
  async delete(id: number) {
    const result = await getConnection()
      .createQueryBuilder()
      .delete()
      .from(UserEntity)
      .where('id=:id', { id })
      .execute();
    return result;
  }

  // 分配角色
  async assginRole(id: number, role: CommonObjectProps) {
    const user: UserEntity = await this.userRepository.findOne({
      where: { id: id },
    });
    if (!user.roles) user.roles = [];
    user.roles.push(role as RoleEntity);

    const result = await getConnection()
      .createQueryBuilder()
      .update(UserEntity)
      .set(user)
      .where('id=:id', { id })
      .execute();

    return result;
  }
}
